package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.UsersService;

import com.joint.core.entity.ManageProInfo;

import com.joint.core.service.ManageProInfoService;
import com.joint.core.service.NumberCreaterService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by zhucx on 2015/8/26.
 */
@ParentPackage("com")
public class AjaxManageproinfoAction extends BaseFlowAction {
    @Resource
    private ManageProInfoService manageProInfoService;

    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private NumberCreaterService numberCreaterService;

    private ManageProInfo manageProInfo;

    protected ArrayList<Map<String,Object>> typesArrayList;

    private int numStatus;
    private Users loginUser;

    /**
     * 建设单位 ec客户名称
     */
    private String clientId;
    /**
     * 联系人 两用
     */
    private String linkmanId;
    /**
     * 项目名称 两用
     */
    private String name;

    /**
     * 项目编号
     */
    private String projectNo;
    /**
     * 建设单位地址
     */
    private String buildAddress;
    /**
     * 项目概况
     */
    private String projectInfo;
    /**
     * 项目计划投资额（万元）
     */
    private double numInventMoney;
    /**
     * 资金来源
     */
    private String moneyFrom;
    /**
     * 招标信息来源
     */
    private String bidFrom;
    /**
     * 备注
     */
    private String remark;

    /**
     * 下一步审批人的Name的集合，用逗号分隔
     */
    private String nextStepApproversName;

    /**
     * 下一步审批人的id的集合，用逗号分隔
     */
    private String nextStepApproversId;
    /**
     * 视图类型
     */
    private String viewtype;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "manageproinfo";
    }


    public String listfordialog(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        pager=manageProInfoService.findByPagerAndProcessState(pager, user, "manageproinfo", FlowEnum.ProcessState.Finished, params);
        List<ManageProInfo> proInfoList;
        if (pager.getTotalCount() > 0){
            proInfoList = (List<ManageProInfo>) pager.getList();
        }else{
            proInfoList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(ManageProInfo mproInfo:proInfoList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",mproInfo.getId());
            rMap.put("name",mproInfo.getName());
            rMap.put("no",mproInfo.getProjectNo());
            rMap.put("create",mproInfo.getCreater().getName());

            String sAddr = "";

            rMap.put("buildAddress" , mproInfo.getBuildAddress());

            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 内嵌视图
     * @return
     */
     public String view(){
        return "view";
    }

    public String view2(){
        return "view2";
    }
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        /*内嵌视图这里要加上
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(parentId)){
            manageProInfo = manageProInfoService.get(parentId);
            params.put("manageProInfo",manageProInfo);
        }*/
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
      //  LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=manageProInfoService.findByPagerAndLimit(false, "manageproinfo", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=manageProInfoService.findByPagerAndFinish( "manageproinfo", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=manageProInfoService.findByPagerAndLimit(true, "manageproinfo", pager, params);
        }

        List<ManageProInfo> proInfoList;
        if (pager.getTotalCount() > 0){
            proInfoList = (List<ManageProInfo>) pager.getList();
        }else{
            proInfoList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(ManageProInfo mproInfo:proInfoList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",mproInfo.getId());
            rMap.put("name",mproInfo.getName());
            rMap.put("no",mproInfo.getProjectNo());

            rMap.put("create",mproInfo.getCreater().getName());
            rMap.put("state",mproInfo.getProcessState().value());

            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            manageProInfo = manageProInfoService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
        }
        return "read";
    }

    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            manageProInfo = manageProInfoService.get(keyId);
        } else {
            Company company = usersService.getCompanyByUser();

            Map<String,Object> rMap = null;
            typesArrayList = new ArrayList<Map<String, Object>>();
            for(Dict typeObj:dictService.listFormDefinedEnable(DictBean.DictEnum.ProInfoCategory, company.getId())){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                typesArrayList.add(rMap);
            }
        }

        return "input";
    }

    private void setData(){


        if(StringUtils.isNotEmpty(keyId)){
            manageProInfo = manageProInfoService.get(keyId);
        }else{
            manageProInfo = new ManageProInfo();
            manageProInfo.setCreater(usersService.getLoginInfo());
        }

        manageProInfo.setName(name);
        Calendar c = Calendar.getInstance();
        manageProInfo.setProjectNo(numberCreaterService.getNumber(ManageProInfo.class.getName(), c.get(Calendar.YEAR) + "", 4, null));

        manageProInfo.setBuildAddress(buildAddress);

        manageProInfo.setProjectInfo(projectInfo);
        manageProInfo.setMoneyFrom(moneyFrom);
        manageProInfo.setBidFrom(bidFrom);
        manageProInfo.setRemark(remark);
        manageProInfo.setNumInventMoney(numInventMoney);
        manageProInfo.setNextStepApproversId(nextStepApproversId);
        manageProInfo.setNextStepApproversName(nextStepApproversName);
        manageProInfo.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                manageProInfoService.update(manageProInfo);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                various.put("curDutyId", curDutyId);
                manageProInfoService.save(manageProInfo, "manageproinfo", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();

        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
       // System.out.println("nextStepApproversId:"+nextStepApproversId);
        ArrayList<String> list = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
        //    System.out.println("uid:"+uid);
            list.add(uid.trim());
        }
        var2.put("approvers", list);    // 会签人Ids
        var2.put("inventMoney", numInventMoney);    // 项目计划投资额（万元）

        if(StringUtils.isEmpty(comment)){
            comment="";
        }

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                manageProInfoService.approve(manageProInfo, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                manageProInfoService.commit(manageProInfo, "manageproinfo", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        manageProInfo = manageProInfoService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                manageProInfoService.approve(manageProInfo, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        manageProInfo = manageProInfoService.get(keyId);
       // Task task=workflowService.getCurrentTask(keyId, usersService.getLoginInfo());
       // Map<String, Object> var2 = new HashMap<String, Object>();
        /*
        int multComplete = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfCompletedInstances");
        int nrOfInstances = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfInstances");
        LogUtil.info("multComplete:"+multComplete);
        LogUtil.info("nrOfInstances:"+nrOfInstances);

        if((double)multComplete/nrOfInstances>0.6){
            var2.put("numStatus", 2);
            LogUtil.info("do:numStatus2");
        } else {
            var2.put("numStatus", 1);
            LogUtil.info("do:numStatus1");
        }*/
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("curDutyId", curDutyId);
        try {
            manageProInfoService.approve(manageProInfo, FlowEnum.ProcessState.Running, var2, curDutyId, comment);
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                ManageProInfo manageProInfo=manageProInfoService.get(keyId);
                manageProInfo.setProcessState(FlowEnum.ProcessState.Finished);
                manageProInfoService.update(manageProInfo);
            }else {
               if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {

                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 3);
               }
            }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
            manageProInfo = manageProInfoService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        var2.put("curDutyId", curDutyId);
        try {
            manageProInfoService.approve(manageProInfo, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            manageProInfo = manageProInfoService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("manageproinfo");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            manageProInfoService.reject(manageProInfo, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            manageProInfo = manageProInfoService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("manageproinfo");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            manageProInfoService.deny(manageProInfo, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public ManageProInfo getManageProInfo() {
        return manageProInfo;
    }

    public void setManageProInfo(ManageProInfo manageProInfo) {
        this.manageProInfo = manageProInfo;
    }

    public ArrayList<Map<String, Object>> getTypesArrayList() {
        return typesArrayList;
    }

    public void setTypesArrayList(ArrayList<Map<String, Object>> typesArrayList) {
        this.typesArrayList = typesArrayList;
    }




    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getLinkmanId() {
        return linkmanId;
    }

    public void setLinkmanId(String linkmanId) {
        this.linkmanId = linkmanId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getProjectNo() {
        return projectNo;
    }

    public void setProjectNo(String projectNo) {
        this.projectNo = projectNo;
    }

    public String getBuildAddress() {
        return buildAddress;
    }

    public void setBuildAddress(String buildAddress) {
        this.buildAddress = buildAddress;
    }

    public String getProjectInfo() {
        return projectInfo;
    }

    public void setProjectInfo(String projectInfo) {
        this.projectInfo = projectInfo;
    }

    public double getNumInventMoney() {
        return numInventMoney;
    }

    public void setNumInventMoney(double numInventMoney) {
        this.numInventMoney = numInventMoney;
    }

    public String getMoneyFrom() {
        return moneyFrom;
    }

    public void setMoneyFrom(String moneyFrom) {
        this.moneyFrom = moneyFrom;
    }

    public String getBidFrom() {
        return bidFrom;
    }

    public void setBidFrom(String bidFrom) {
        this.bidFrom = bidFrom;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }



    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getNextStepApproversName() {
        return nextStepApproversName;
    }

    public void setNextStepApproversName(String nextStepApproversName) {
        this.nextStepApproversName = nextStepApproversName;
    }

    public String getNextStepApproversId() {
        return nextStepApproversId;
    }

    public void setNextStepApproversId(String nextStepApproversId) {
        this.nextStepApproversId = nextStepApproversId;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }


    public String getViewtype() {


        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }


}

